package com.example.SecondStore.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.example.SecondStore.config.AliConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@CrossOrigin
@RestController
public class OssFileUploadController  extends ApiController {

    @Autowired
    private AliConfig aliConfig;

    @PostMapping("/ossUpload")
    public R upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {


        if (StringUtils.isEmpty(aliConfig.getEndpoint()) || StringUtils.isEmpty(aliConfig.getBucket())) {
            return R.failed("上传不成功");
        }

        // 获取上传的文件名和文件流
        String fileName = multipartFile.getOriginalFilename();
        InputStream fileStream = multipartFile.getInputStream();

        // 创建阿里云 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(aliConfig.getEndpoint(), aliConfig.getId(), aliConfig.getSecret());

        // 执行文件上传操作
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliConfig.getBucket(), fileName, fileStream);
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

        // 关闭阿里云 OSS 客户端
        ossClient.shutdown();

        // 构建上传成功的文件 URL
        String fileUrl = "https://" + aliConfig.getBucket() + "." + aliConfig.getEndpoint() + "/" + fileName;


        return R.ok(fileUrl);


    }
}